package com.gyg.controller;


import com.gyg.client.CloudMessageClient;
import com.gyg.domain.CloudUser;
import com.gyg.enums.SessionEnum;
import com.gyg.returns.RespCode;
import com.gyg.returns.RespEntity;
import com.gyg.utils.OSSUtil;
import com.gyg.vo.param.MessageParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * <p>
 * 云盘消息表 前端控制器
 * </p>
 *
 * @author gyg
 * @since 2021-04-14
 */
@RestController
@RequestMapping("/cloud-message")
@Api(value = "公告模块", tags = "公告模块")
@Slf4j
public class CloudMessageController {

    @Resource
    private CloudMessageClient cloudMessageClient;

    @Resource
    private OSSUtil ossUtil;

    @ApiOperation(value = "公告列表")
    @GetMapping("/list")
    public RespEntity cloudMessageList() {
        RespEntity respEntity = cloudMessageClient.cloudMessageList();
        return respEntity;
    }

    /**
     * OSS文件上传
     * */
    @RequestMapping("/upload")
    @ApiOperation(value = "上传公告照片")
    public RespEntity upload(MultipartFile file){
        String fileName = ossUtil.getFileName("cloud/message/", file.getOriginalFilename());
        String url = ossUtil.getUrl(fileName);
        try {
            byte[] bytes = file.getBytes();
            ossUtil.upload(fileName, bytes);
            return new RespEntity(RespCode.SUCCESS, url);
        } catch (Exception e) {
            log.error("文件上传失败", e.getMessage());
            return new RespEntity(RespCode.UPLOAD_ERROR);
        }
    }

    @PostMapping("/insert")
    @ApiOperation(value = "发布公告")
    public RespEntity insertNotice(MessageParam messageParam, HttpSession session) {
        CloudUser cloudUser = (CloudUser) session.getAttribute(SessionEnum.USER.getCode());
        if (Objects.nonNull(cloudUser)) {
            messageParam.setUserId(cloudUser.getId());
        }
        RespEntity respEntity = cloudMessageClient.insertNotice(messageParam);
        return respEntity;
    }

}
